from flask import current_app
from flask import g
from flask import jsonify
from flask import redirect
from flask import request
from flask import session

from info import constants, db
from info.libs.qiniu.image_storage import storage
from info.models import User
from info.modules.profile import pro_blu
from info.response_code import RET
from info.utils.common import user_login


@pro_blu.route('/api/v1.0/user')
@user_login
def base_info():
    # 获取用户
    user = g.user
    if not user:
        return redirect("/")

    data = {
        'name': user.name,
        'mobile': user.mobile,
        'avatar_url': constants.QINIU_DOMIN_PREFIX + user.avatar_url if user.avatar_url else ""
    }

    return jsonify(errno=RET.OK, errmsg="OK", data=data)


@pro_blu.route('/api/v1.0/user/name', methods=['POST'])
@user_login
def user_name():
    user = g.user
    name = request.json.get('name')
    user.name = name

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存失败")

    return jsonify(errno=RET.OK, errmsg="OK")


@pro_blu.route('/api/v1.0/user/avatar',methods=['POST'])
@user_login
def user_avatar():
    user = g.user
    try:
        avatar = request.files.get("avatar").read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        key = storage(avatar)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传头像失败")

    user.avatar_url = key

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存失败")

    return jsonify(errno=RET.OK, errmsg="OK", data={"avatar_url": constants.QINIU_DOMIN_PREFIX + key})
